package com.ecric.http;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ecric.http.OkHttp3.package3.OkHttpsUtil;
import com.ecric.http.OkHttp3.package3.RequestCallback;
import com.ecric.http.http.WeatherBean;
import com.ecric.http.http.WeatherBean2;
import com.google.gson.Gson;

import org.androidannotations.annotations.AfterExtras;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.SupposeBackground;
import org.androidannotations.annotations.SupposeUiThread;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EncodingUtils;

import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.Request;
import okhttp3.Response;

@EActivity(R.layout.activity_main)
public class MainActivity extends AppCompatActivity {

    @ViewById(R.id.img_http)
    ImageView img;
    /** 会在子类的init_方法中被初始化 */
    @Bean
    WeatherBean weatherBean;
    /**从别的界面跳转过来，取intent中值 ，括号中的字符串将会作为key 如果没有指定，那么变量名将会作为key */
    @Extra("weatherPath")
    String weatherPath = "http://www.sojson.com/open/api/weather/json.shtml?city=北京";
    @ViewById
    TextView txt_http;
    @ViewById
    TextView txt_http2;

//    private HttpURLConnection connection;
    /** 输出流 */
//    private DataOutputStream dos;

    public static final String APP_KEY = "99603ed441919f883861b70138c723c9";
    private String  path = "https://way.jd.com/he/freeweather";
    private HashMap<String, String> params = new HashMap<>();

    @AfterViews
    void initData(){
//        getDataFromNet();
        params.put("appkey",APP_KEY);
        params.put("city","北京");
        getNetDataByPost(path,params);

        OkHttpsUtil.getInstance()
                .post()
                .url(path)
                .addParam("","")
                .build()
                .enqueue(new RequestCallback() {
                    @Override
                    public void onBefore() {

                    }

                    @Override
                    public void onFailure(Request request, Exception e) {

                    }

                    @Override
                    public void onResponse(Response response) {

                    }

                    @Override
                    public void onError(Response response, int code) {

                    }
                });

    }

    /***
     * 该方法将会获取外部数据后被调用
     */
    @AfterExtras
    void getExtrasData(){

    }

    /**
     * 启动子线程请求网络数据，用来设置子线程的id
     */
    @Background(serial = "serial1")
    void getDataFromNet(){
        long  time  = System.currentTimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH : mm : ss");
        try {
            // String weatherPath = "http://www.sojson.com/open/api/weather/json.shtml?city=北京";
            URL url = new URL(weatherPath);
            HttpURLConnection  connection = (HttpURLConnection) url.openConnection();
            connection.setUseCaches(false); // 设置是否启用缓存,post请求不能使用缓存.
            connection.setRequestMethod("GET");

            connection.setRequestProperty("Cache-Control","no-cache");
            //表示接受数据的类型 如果可以接受的序列化的java对象，添加类型application/x-www-form-urlencoded
//            connection.setRequestProperty("Accept","image/gif, image/jpeg, image/pjpeg, image/pjpeg, " +
//                    "application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, " +
//                    "application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, " +
//                    "application/vnd.ms-powerpoint, application/msword,text/xml , text/html ,application/json ,*/*");
            connection.setRequestProperty("Accept-Language","zh-cn");
            connection.setRequestProperty("Accept-Charset","UTF-8");
            //
            connection.setRequestProperty("Accept-Encoding","gzip, deflate");
            connection.setRequestProperty("Connection","Keep-Alive");
            connection.setRequestProperty("Date",format.format(new Date(time)));
            //指明实体正文的长度，以字节方式存储的十进制数字来表示
//            connection.setRequestProperty("Content-Length","23330");
            //指明发送给接收者的实体正文的媒体类型
//            connection.setRequestProperty("Content-Type","application/json,text/xml,text/html;charset=utf-8");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            Map<String,List<String>> listMap =  connection.getRequestProperties();
            Log.e("请求头部",listMap.toString());
            connection.connect();
            int code = connection.getResponseCode();
            String result;
            if (code == HttpURLConnection.HTTP_OK) { // 若响应码以2开头则读取响应头总的返回信息
                BufferedInputStream  bis = new BufferedInputStream(connection.getInputStream());
                ByteArrayBuffer arrayBuffer = new ByteArrayBuffer(1024);
                int length = -1;
                while ((length = bis.read()) != -1) {
                    arrayBuffer.append(length);
                }
                result = EncodingUtils.getString(arrayBuffer.toByteArray(), "UTF-8");
                Gson gson = new Gson();
                final WeatherBean  weatherBean =  gson.fromJson(result,WeatherBean.class);
                updateUi(weatherBean);

            } else { // 若响应码不以2开头则返回错误信息.
                result = "error";
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    @Background
    void getNetDataByPost(String path , HashMap<String, String> attribute){
        long  time  = System.currentTimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH : mm : ss");
        try {
            URL url = new URL(path);
            HttpURLConnection  connection = (HttpURLConnection) url.openConnection();
            connection.setUseCaches(false); // 设置是否启用缓存,post请求不能使用缓存.
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Cache-Control","no-cache");
            //表示接受数据的类型 如果可以接受的序列化的java对象，添加类型application/x-www-form-urlencoded
//            connection.setRequestProperty("Accept","image/gif, image/jpeg, image/pjpeg, image/pjpeg, " +
//                    "application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, " +
//                    "application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, " +
//                    "application/vnd.ms-powerpoint, application/msword,text/xml , text/html ,application/json ,*/*");
            connection.setRequestProperty("Accept-Language","zh-cn");
            connection.setRequestProperty("Accept-Charset","UTF-8");
            //
            connection.setRequestProperty("Accept-Encoding","gzip, deflate");
            connection.setRequestProperty("Connection","Keep-Alive");
            connection.setRequestProperty("Date",format.format(new Date(time)));
            //指明实体正文的长度，以字节方式存储的十进制数字来表示
//            connection.setRequestProperty("Content-Length","23330");
            //指明发送给接收者的实体正文的媒体类型
//            connection.setRequestProperty("Content-Type","application/json;charset=utf-8");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.connect();

            DataOutputStream  dos = new DataOutputStream(connection.getOutputStream());
            StringBuilder  builder  =  new StringBuilder();
            // attribute 为 HashMap<String, String>
            Set<String> set  = attribute.keySet();
            Iterator<String> stringIterator  = set.iterator();
            while (stringIterator.hasNext()){
                String key = stringIterator.next();
                String param = key + "=" + URLEncoder.encode(attribute.get(key)) + "&";
                builder.append(param);
            }
            dos.writeBytes(builder.toString().substring(0, builder.toString().length() - 1));

            int code = connection.getResponseCode();
            // {null=[HTTP/1.1 200 OK], Cache-Control=[max-age=0], Connection=[close],
            // Content-Length=[4765], Content-Type=[application/json;charset=utf-8],
            // Date=[Fri, 08 Sep 2017 02:01:44 GMT], Expires=[Fri, 08 Sep 2017 02:01:44 GMT],
            // Server=[JDWS/1.0.0], X-Android-Received-Millis=[1504836104059],
            // X-Android-Response-Source=[NETWORK 200], X-Android-Sent-Millis=[1504836103886]}
            Map<String,List<String>> listMap = connection.getHeaderFields();
            Log.i("===========>listMap: ",listMap.toString());
            String result;
            if (code == HttpURLConnection.HTTP_OK) { // 若响应码以2开头则读取响应头总的返回信息
                BufferedInputStream  bis = new BufferedInputStream(connection.getInputStream());
                ByteArrayBuffer arrayBuffer = new ByteArrayBuffer(1024);
                int length = -1;
                while ((length = bis.read()) != -1) {
                    arrayBuffer.append(length);
                }
                result = EncodingUtils.getString(arrayBuffer.toByteArray(), "UTF-8");
                Gson gson = new Gson();
                final WeatherBean2 weatherBean =  gson.fromJson(result,WeatherBean2.class);
                //更新UI
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (null == weatherBean || null == weatherBean.getResult() ||
                                null == weatherBean.getResult().getHeWeather5() || null == weatherBean.getResult().getHeWeather5().get(0) ||
                                null == weatherBean.getResult().getHeWeather5().get(0).getSuggestion() ||
                                null == weatherBean.getResult().getHeWeather5().get(0).getSuggestion().getUv()){
                            return;
                        }
                        txt_http2.setText(weatherBean.getResult().getHeWeather5().get(0).getSuggestion().getUv().toString());
                    }
                });
            } else { // 若响应码不以2开头则返回错误信息.
                result = "error";
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @UiThread(propagation = UiThread.Propagation.REUSE)
    void updateUi(WeatherBean bean){
        if (null != bean){
            txt_http.setText(bean.getCity() + " 温度是:" + bean.getData().getWendu());
        }
    }

    /**
     * 我们知道在子线程中不能直接修改view，如果修改了那么就抛出异常，
     * 而这个异常可以用SupposeBackground注解的方法扑捉到
     */
    @SupposeBackground
    void someMethodThatShouldNotBeCalledFromUiThread() {
        //if this method will be called from the UI-thread an exception will be thrown
    }

    @SupposeBackground(serial = {"serial1", "serial2"})
    void someMethodThatShouldBeCalledFromSerial1OrSerial2() {
        //if this method will be called from another thread then a background thread with a
        //serial "serial1" or "serial2", an exception will be thrown
    }

    @SupposeUiThread
    void someMethodThatShouldBeCalledOnlyFromUiThread() {
        //if this method will be called from a background thread an exception will be thrown
        Toast.makeText(this, "Ui异常", Toast.LENGTH_SHORT).show();
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }



}
